package com.j2ee.student.controller;

import com.j2ee.student.mapper.UserMapper;
import com.j2ee.student.util.JWTUtil;
import com.j2ee.student.util.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/**
 * @Description: TODO
 * @author: 高思源
 * @date: 2022年05月27日 13:46
 */

@RestController
public class LoginController {

    @Resource
    private UserMapper userMapper;

    @PostMapping("/login")
    public R login(@RequestParam("username") String username, @RequestParam("password") String password){

        String realPassword = userMapper.getPassword(username);
        if (realPassword == null){
            return R.fail().setData("用户名错误");
        }
        else if(!realPassword.equals(password)){
            return R.fail().setData("密码错误");
        }
        else return R.ok().setData(JWTUtil.createToken(username));

    }

    @RequestMapping(path = "/unauthorized/{message}")
    public R unauthorized(@PathVariable String message) throws UnsupportedEncodingException {
        return R.fail().setCode(402).setData(message);
    }
}
